/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package br.com.foxinline.servlet;

import br.com.foxinline.modelo.Anexo;
import br.com.foxinline.servico.AnexoServico;
import br.com.foxinline.servico.ImovelServico;
import br.com.foxinline.util.Base64;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import java.io.BufferedReader;
import java.io.IOException;
import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author roniere
 */
@WebServlet(name = "receiverAnnexServlet", urlPatterns = "/receiverAnnexServlet/*")
public class ReceiverAnnexServlet extends HttpServlet {

    private static final long serialVersionUID = 1L;
    @EJB
    private AnexoServico anexoServico;
    @EJB
    private ImovelServico imovelServico;

    @Override
    protected void doGet(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        String requestData = processRequest(request);

//        System.err.println(""+requestData);
        
        Gson gson = new GsonBuilder().setDateFormat("dd/MM/yyyy HH:mm:ss").create();

        requestData = requestData.replace("\"description\":", "\"nome\":");
        requestData = requestData.replace("\"filebyte\":", "\"arquivo\":");
        requestData = requestData.replace("\"type\":", "\"tipo\":");

        //ANEXO RECEBIDO
        Anexo annex = gson.fromJson(requestData, Anexo.class);
        //ANEXO NA BASE
        Anexo a = anexoServico.findUUID(annex.getCod());

        if(a == null){
            System.err.println("Não existe: "+annex.getCod());
        }else{
            System.err.println("Existe: "+annex.getCod());
        }
        
        if (a != null){
            a.setAtualizado(true);
            a.setNome("SUBSTITUIR");
            a.setUrlantiga(a.getNome());
            a.setUrl(null);
            a.setContent(annex.getContent());
            a.setArquivo(Base64.decode(annex.getContent()));
            anexoServico.update(a);

        }

    }

    private String processRequest(HttpServletRequest request) {
        StringBuffer jb = new StringBuffer();
        String line = null;
        try {
            BufferedReader reader = request.getReader();
            while ((line = reader.readLine()) != null) {
                jb.append(line);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return jb.toString();

    }
}
